import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

export function loadIconImage(file: File, { iconSize = 128 } = {}): Promise<ImageData> {
  return new Promise(async (resolve, reject) => {
    // 创建一个Image对象
    const image = new Image();

    // 设置Image对象的源为文件对象
    image.src = URL.createObjectURL(file);

    // 当图像加载完成后，将其绘制到canvas上
    image.onload = function () {
      // 创建canvas元素
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');

      // 设置canvas的尺寸与图像尺寸相同
      canvas.width = iconSize;
      canvas.height = iconSize;

      const width = image.naturalWidth;
      const height = image.height;

      if (ctx) {
        // 将图像绘制到canvas上
        if (width > height) {
          const r = width / iconSize;
          ctx.drawImage(image, 0, (iconSize - height / r) / 2, iconSize, height / r); // 绘制原始图像
        } else {
          const r = height / iconSize;
          ctx.drawImage(image, (iconSize - width / r) / 2, 0, width / r, iconSize);
        }

        // 获取imageData
        const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

        // 这里可以对imageData进行操作，例如处理图像数据

        // 清理：释放创建的URL对象
        URL.revokeObjectURL(image.src);

        // 返回imageData
        resolve(imageData);
      }
    };

    // 处理图像加载失败的情况
    image.onerror = function (err) {
      reject(err);
    };
  });
}

export function getRandomNumber(min: number, max: number) {
  const randomNumber = Math.random();
  const scaledRandomNumber = min + (max - min) * randomNumber;
  return scaledRandomNumber;
}

export function waitEleRender(
  selector: string,
  timeout: number,
  interval = 200,
): Promise<Element | null> {
  return new Promise((resolve) => {
    let timer: number | undefined = undefined;
    const ele = document.querySelector(selector);
    if (ele) {
      resolve(ele);
      return;
    }
    timer = setInterval(() => {
      const ele = document.querySelector(selector);
      if (ele) {
        resolve(ele);
        clearInterval(timer);
      }
    }, interval) as unknown as number;

    setTimeout(() => {
      resolve(null);
      clearInterval(timer);
    }, timeout);
  });
}

export function getXPath(element: HTMLElement): string | undefined {
  if (element.id) {
    return `//*[@id="${element.id}"]`;
  }
  if (element === document.documentElement) {
    return '/html';
  }
  if (element === document.body) {
    return '/html/body';
  }
  if (!element.parentNode) {
    return '/' + element.tagName.toLowerCase();
  }
  let index = 0;
  const nodes = element.parentNode.children;
  for (const node of nodes) {
    if (node === element) {
      if (node.parentNode) {
        return (
          getXPath(node.parentNode as HTMLElement) +
          '/' +
          element.tagName.toLowerCase() +
          `[${index + 1}]`
        );
      }
    }
    if (node.tagName === element.tagName) {
      index++;
    }
  }
}

export function delay(time: number) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(time);
    }, time);
  });
}

export async function getCurrentTab() {
  const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
  return tabs[0];
}
